home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2611 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.1 KB  |  83 lines

  1. Path: atglab.bls.com!Alun.Champion
  2. From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: using const for structs?
  5. Date: 18 Jan 1996 19:01:11 GMT
  6. Organization: Computer People Inc.
  7. Message-ID: <ALUN.CHAMPION.96Jan18140111@g7240065.bridge.bst.bls.com>
  8. References: <4dm36c$c1h@zdi.informatik.uni-stuttgart.de>
  9. NNTP-Posting-Host: bstfirewall.bst.bls.com
  10. In-reply-to: Gerhard Muth's message of 18 Jan 1996 18:23:08 GMT
  11.  
  12. In article <4dm36c$c1h@zdi.informatik.uni-stuttgart.de> Gerhard Muth <muth> writes:
  13.  
  14. :// If i try to compile it on a HP 700 with
  15. :// $ CC const_struct.C
  16. :// i get the following error message:
  17. :// CC: "const_struct.C", line 35: error: cannot make a box (1284)
  18. ://
  19. :// I think, that i have to write a 2-parameter constructor,
  20. :// but the book does not tell anything about that. It just says:
  21. ://
  22. ://     "The #define directive is limited to defining simple
  23. ://      constants. The const statement can define almost any
  24. ://      type of C++ constant including things such as
  25. ://      structure classes."
  26. ://
  27. :// Question: Is the book wrong or is the compiler just bad?
  28.  
  29. : struct box {
  30.        float width, heigth; // float was int before
  31. : };
  32.  
  33. : const box blue_box();
  34.  
  35. I don't think this line does what you expected - this declares
  36. a function that returns a const box and takes no parameters.
  37. I believe you meant:
  38.  
  39.   const box blue_box;
  40.  
  41. : const box pink_box(1.0, 4.5); // this is line 35
  42.  
  43. This is a constructor call which you have not provided for struct
  44. box. The book is not wrong and compiler is not bad. You can declare
  45. initialise this struct like:
  46.  
  47.   const box pink_box = { 1.0, 4.5 };
  48.  
  49. or you can define a constructor for struct box:
  50.  
  51.   struct box {
  52.       box(float w = 0.0, float h = 0.0) : width(w), height(h)
  53.       { }
  54.  
  55.       float width, heigth; // float was int before
  56.   };
  57.  
  58. now this works:
  59.  
  60.   const box pink_box(1.0, 4.5);
  61.  
  62. and so does:
  63.  
  64.   const box blue_box;
  65.  
  66. and:
  67.  
  68.   const box green_box(4.0);
  69.  
  70. : void main(void) {}
  71.  
  72. This has undefined behaviour - main should be declared
  73.  
  74.   int main(void)
  75. or
  76.   int main(int argc, char* argv[])
  77.  
  78. Hope this helps
  79. Regards
  80.    -A.
  81. -- 
  82. | A.Champion                |
  83.